import axios from 'axios'
import qs from 'qs'
import Promise from 'Promise'
import Vue from 'vue'

let api = {}
let ajaxUrl = 'http://127.0.0.1:8080'
if (process.env.NODE_ENV === 'development') {
  ajaxUrl = 'http://127.0.0.1:8080'
}

api.http = axios.create({
  timeout: 30000
})

// 添加请求拦截器
api.http.interceptors.request.use(
  function (config) {
    Vue.$vux.loading.show({
      text: '加载中'
    })
    // config.headers['Accept'] = 'application/x.edu.v1+json';
    if (config.method === 'post' || config.method === 'put') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(config.data)
    }
    return config
  },
  function (error) {
    setTimeout(() => {
      Vue.$vux.loading.hide()
      Vue.$vux.toast.show({
        text: '加载超时',
        position: 'middle',
        type: 'warn'
      })
    }, 3000)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.http.interceptors.response.use(
  function (response) {
    Vue.$vux.loading.hide()
    if (response.status === 200) {
      console.log(response.data)
      if (response.data.status === 401) {
        Vue.$vux.toast.show({
          width: '20em',
          text: response.data.status + '您的会话已过期，请重新登陆',
          position: 'middle',
          type: 'warn'
        })
      }
      return response.data
    }
    return response
  },
  function (error) {
    setTimeout(() => {
      Vue.$vux.loading.hide()
      Vue.$vux.toast.show({
        text: '请求失败',
        position: 'middle',
        type: 'warn'
      })
    }, 1000)
    return Promise.reject(error.response.data.message)
  }
)

api.get = function (url) {}

api.post = function (url, params) {}

api.put = function (url, params) {}

api.getLocalTime = function (nS) {
  return new Date(parseInt(nS) * 1000)
}

api.url = {
  // 登录
  login: ajaxUrl + '/auth',
  list: ajaxUrl + '/list'
}

export default api
